package org.example.leetCode;

/**
 * 3. 无重复字符的最长子串
 * 给定一个字符串 s ，请你找出其中不含有重复字符的 最长 子串 的长度。
 */
public class Code3 {
    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        int result = 0;
        int[] charIndex = new int[256];
        for (int left = 0, right = 0; right < len; right++) {
            char c = s.charAt(right);
            //出现重复，跳过
            left = Math.max(left, charIndex[c]);
            result = Math.max(result, right - left + 1);
            //记录如果出现重复字符时左指针下一个指向的位置
            charIndex[c] = right + 1;
        }
        return result;
    }

    public static void main(String[] args) {
        Code3 solution = new Code3();

        // 测试用例1
        String s1 = "abcabcbb";
        int result1 = solution.lengthOfLongestSubstring(s1);
        System.out.println("输入: \"" + s1 + "\"");
        System.out.println("输出: " + result1);
        System.out.println("解释: 最长无重复子串是 \"abc\"，长度为 3");
        System.out.println();

        // 测试用例2
        String s2 = "bbbbb";
        int result2 = solution.lengthOfLongestSubstring(s2);
        System.out.println("输入: \"" + s2 + "\"");
        System.out.println("输出: " + result2);
        System.out.println("解释: 最长无重复子串是 \"b\"，长度为 1");
        System.out.println();

        // 测试用例3
        String s3 = "pwwkew";
        int result3 = solution.lengthOfLongestSubstring(s3);
        System.out.println("输入: \"" + s3 + "\"");
        System.out.println("输出: " + result3);
        System.out.println("解释: 最长无重复子串是 \"wke\"，长度为 3");
        System.out.println();

        // 测试用例4
        String s4 = "";
        int result4 = solution.lengthOfLongestSubstring(s4);
        System.out.println("输入: \"" + s4 + "\"");
        System.out.println("输出: " + result4);
        System.out.println("解释: 空字符串，长度为 0");
        System.out.println();

        // 测试用例5
        String s5 = "abcdef";
        int result5 = solution.lengthOfLongestSubstring(s5);
        System.out.println("输入: \"" + s5 + "\"");
        System.out.println("输出: " + result5);
        System.out.println("解释: 整个字符串无重复字符，长度为 6");
    }
}
